<template>
  <common-list>
    <common-search slot="search" @search="handleQuery" @reset="resetQuery">
      <el-form
        @submit.native.prevent
        :model="queryParams"
        ref="queryForm"
        :inline="true"
        @enter="handleQuery"
        label-width="75px"
      >
        <el-form-item label="订阅名称" prop="jobName">
          <common-input
            v-model="queryParams.jobName"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="订阅报告" prop="jobReportNames">
          <common-input
            v-model="queryParams.jobReportNames"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="收件人邮箱" prop="jobEmails">
          <common-input
            v-model="queryParams.jobEmails"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="订阅周期" prop="jobCycle">
          <el-select v-model="queryParams.jobCycle" filterable>
            <el-option label="全部" :value="null"></el-option>
            <el-option
              v-for="item in executionCycleTypeArr"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-select v-model="queryParams.status">
            <el-option label="全部" :value="null"></el-option>
            <el-option label="启用" value="0"></el-option>
            <el-option label="停用" value="1"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </common-search>

    <el-row :gutter="10" class="mb8" slot="tools">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          @click="handleAdd"
          v-hasPermi="['report:job:add']"
          >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          :disabled="ids.length < 1"
          @click="handleDelete"
          v-hasPermi="['report:job:remove']"
          >批量删除
        </el-button>
      </el-col>
    </el-row>

    <common-table
      v-loading="loading"
      slot="content"
      :data="taskList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        label="订阅名称"
        align="left"
        prop="jobName"
        show-overflow-tooltip
      />
      <el-table-column
        label="订阅报告"
        align="left"
        prop="jobReportNames"
        show-overflow-tooltip
      >
        <template slot-scope="scope">
          {{ getJobNames(scope.row) }}
        </template>
      </el-table-column>
      <el-table-column
        label="收件人邮箱"
        align="left"
        prop="jobEmails"
        show-overflow-tooltip
        width="120"
      >
        <template slot-scope="scope">
          {{ getEmails(scope.row) }}
        </template>
      </el-table-column>
      <el-table-column
        label="订阅周期"
        align="left"
        prop="jobCycleString"
        width="210"
      />
      <el-table-column
        label="创建时间"
        align="left"
        prop="createTime"
        width="180"
      />

      <el-table-column label="状态" align="left" prop="status" width="100">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status === '0'" type="success">启用 </el-tag>
          <el-tag v-if="scope.row.status === '1'" type="danger">停用</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="left" width="220px">
        <template slot-scope="scope">
          <el-button
            type="text"
            @click="handleView(scope.row)"
            v-hasPermi="['report:job:getInfo']"
            >详情
          </el-button>
          <el-button
            type="text"
            v-hasPermi="['report:job:changeStatus']"
            @click="handleShake(scope.row)"
            :disabled="scope.row.isDisabledForShake"
          >
            <span v-if="scope.row.status === '1'">启用</span>
            <span v-if="scope.row.status === '0'">停用</span>
          </el-button>

          <el-button
            type="text"
            @click="handleAdd(scope.row)"
            v-hasPermi="['report:job:edit']"
            >编辑
          </el-button>

          <el-button
            type="text"
            @click="handleHistory(scope.row)"
            v-hasPermi="['report:job:getHis']"
            >历史记录
          </el-button>

          <el-button
            type="text"
            @click="handleDelete(scope.row)"
            v-hasPermi="['report:job:remove']"
            >删除
          </el-button>
        </template>
      </el-table-column>
    </common-table>

    <pagination
      slot="pagination"
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <task-add
      ref="taskAdd"
      @submitForm="submitForm"
      :executionCycleTypeArr="executionCycleTypeArr"
    ></task-add>

    <task-detail ref="taskDetail"></task-detail>

    <task-history
      v-if="taskHistory"
      @back="taskHistory = false"
      :jobId="jobId"
    />
  </common-list>
</template>

<script>
import {
  fetchList,
  getInfo,
  updateStatus,
  jobDelete,
} from "@/api/screenConfig/subscribe/index";
import TaskAdd from "./components/taskAdd.vue";
import TaskDetail from "./components/taskDetail.vue";
import TaskHistory from "./components/taskHistory.vue";
import BaseList from "@/mixins/BaseList";
import { CYCLEARR, DAYARR } from "@/utils/constant";
import { getJobCycleString } from "@/utils/cycleFun";
export default {
  mixins: [BaseList],
  components: {
    TaskAdd,
    TaskDetail,
    TaskHistory,
  },
  data() {
    return {
      ids: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        jobName: null,
        jobCycle: null,
        status: null,
        jobReportNames: null,
        jobEmails: null,
      },
      total: 0,
      taskList: [],
      taskHistory: false,
      jobId: "",
      loading: false,
      executionCycleTypeArr: CYCLEARR,
      dayArr: DAYARR,
    };
  },
  created() {
    this.getList();
  },
  methods: {
    getList() {
      this.loading = true;
      fetchList({ ...this.queryParams, sourceType: "report_center" })
        .then((res) => {
          if (res && res.code === 200) {
            this.taskList = res.rows.reduce((r, c) => {
              r.push({
                ...c,
                isDisabledForShake: false,
                jobCycleString: getJobCycleString(c),
              });
              return r;
            }, []);

            this.total = res.total;
          } else {
            this.taskList = [];
            this.total = 0;
            this.handleListTips(res);
          }
        })
        .catch(() => {
          this.taskList = [];
          this.total = 0;
        })
        .finally(() => {
          this.loading = false;
        });
    },

    getJobNames(row) {
      let jobNamesArr = row.jobReportNames.split(",");
      if (jobNamesArr.length > 1) {
        return jobNamesArr[0] + " 等" + jobNamesArr.length + "个报告";
      }
      return jobNamesArr[0];
    },

    getEmails(row) {
      let emailsArr = row.jobEmails.split(",");
      if (emailsArr.length > 1) {
        return emailsArr[0] + " 等" + emailsArr.length + "个收件人";
      }
      return emailsArr[0];
    },

    // 启停
    changeStatus(row) {
      return new Promise((resolve, reject) => {
        let params = {
          jobId: row.jobId,
          status: row.status === "0" ? "1" : "0",
          sourceType: "report_center",
        };
        updateStatus(params)
          .then((res) => {
            if (res && res.code === 200) {
              this.queryParams.pageNum = 1;
              this.$GlobalSuccessMessage("操作成功");
              resolve(res);
              this.getList();
            } else {
              this.$GlobalErrorConfirm("操作失败", res.msg).then();
              reject();
            }
          })
          .catch(() => reject());
      });
    },

    handleHistory(row) {
      this.jobId = row.jobId;
      this.taskHistory = true;
    },

    handleView(row) {
      this.$refs.taskDetail.show(row);
    },

    handleAdd(row) {
      if (row.jobId && row.status === "0") {
        this.$GlobalErrorConfirm("编辑失败", "启用状态下不允许编辑");
        return;
      }
      this.$refs.taskAdd.show(row ? { ...row } : {});
    },

    handleDelete(row) {
      if (row && row.status === "0") {
        this.$GlobalErrorConfirm("警告", "启用状态下不允许删除");
        return;
      }

      let enableStatus = this.taskList.find((v) => {
        return this.ids.includes(v.jobId) && v.status === "0";
      });

      if (enableStatus) {
        this.$GlobalErrorConfirm("删除失败", "启用状态下不允许删除");
        return;
      }

      const ids = row.jobId || this.ids.join(",");

      this.$GlobalDeleteConfirm()
        .then(() => {
          jobDelete({ ids, sourceType: "report_center" }).then((res) => {
            if (res && res.code == 200) {
              this.$GlobalSuccessMessage("删除成功");
              if (
                this.queryParams.pageNum > 1 &&
                ids.split(",").length === this.taskList.length
              ) {
                this.queryParams.pageNum -= 1;
              }
              this.getList();
            } else {
              this.$GlobalErrorConfirm("删除失败", res.msg);
            }
          });
        })
        .catch(() => {});
    },

    submitForm() {
      this.getList();
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.jobId);
    },

    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    resetQuery() {
      this.queryParams = this.$options.data().queryParams;
    },
  },
};
</script>

<style lang="scss"></style>
